<?php
class NMailer {
	
	/**
	 * Send Mail
	 *
	 * @param array $options
	 * possible index: from, replyTo, to, subject, message
	 * @return void
	 * @author Eleven
	 */
	public static function SendMail($options)
	{
		$from = "From: " . (isset($options['from']) ? $options['from'] : Yii::app()->params['adminEmail']);
		$replyTo = "Reply-To: " . (isset($options['replyTo']) ? $options['replyTo'] : Yii::app()->params['adminEmail']);
		$to = (isset($options['to']) ? $options['to'] : Yii::app()->params['adminEmail']);
		$headers=$from . "\r\n" . $replyTo;
		$subject = isset($options['subject']) ? $options['subject'] : "Testing Email";
		$message = isset($options['message']) ? $options['message'] : "Testing Content";
		
		mail($to,$subject,$message,$headers);
	}

	/* If we dont pass in $username & $password, a WebSetting value of key 'system-email-account' will be used */
	public static function SetupSmtpMail($username='', $password='', $debug = false)
	{
		Yii::import('application.extensions.phpmailer.PHPMailer');
		Yii::import('application.extensions.phpmailer.Smtp');
		$host = Yii::app()->request->serverName == 'localhost' ? 'localhost.com' : Yii::app()->request->serverName;
		
		if($username=='' && $password=='')
		{
			$systemEmailAccount = NMailer::GetMailAccount();
			$username = $systemEmailAccount[0];
			$password = $systemEmailAccount[1];
		}

		$mail = new PHPMailer(true);
		$mail->CharSet = "UTF-8";
		$mail->IsSMTP(); // set mailer to use SMTP
		$mail->Host = "smtp.gmail.com"; // specify main and backup server
		$mail->Port = 465; // set the port to use
		$mail->SMTPAuth = true; // turn on SMTP authentication
		$mail->SMTPSecure = 'ssl';
		$mail->Username = $username; // your SMTP username or your gmail username
		$mail->Password = $password; // your SMTP password or your gmail password	
		$mail->Sender = 'no-reply@'.$host;
		$mail->From = 'no-reply@'.$host;
		$mail->FromName = Yii::t('app','Ban quản trị') . ' - ' . Yii::app()->name;
		$mail->WordWrap = 50; // set word wrap
		$mail->IsHTML(true); // send as HTML
		if($debug) $mail->SMTPDebug = 2;
		return $mail;
	}

	// This email account is used to send email out
	public static function GetMailAccount()
	{
		$systemEmailAccount = WebSetting::get('system-email-account');
		$systemEmailAccount = explode("\r\n", $systemEmailAccount);
		if(count($systemEmailAccount)<2) throw new CException(404, Yii::t('backend',Yii::t('app','Thông số cài đặt <strong>{thongso}</strong> không hợp lệ.', array('{thongso}'=>'system-email-acocunt'))));
		return $systemEmailAccount;
	}
}